package com.fpf.controller.advice;

import com.fpf.controller.vo.response.ResultCode;
import com.fpf.controller.vo.response.ResultVO;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 统一请求参数异常处理
 * 针对json格式的数据传输，进行数据参数校验，@Validated @RequestBody
 */
@RestControllerAdvice("com.fpf.controller")
public class MethodArgumentExceptionAdvice {
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultVO requestParamExceptionHandler(MethodArgumentNotValidException e){
        // 从异常对象中拿到ObjectError对象
        List<ObjectError> allErrors=e.getBindingResult().getAllErrors();
        List<String> errors=allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return new ResultVO(ResultCode.VALIDATE_ERROR, String.join(",",errors));
    }
}
